import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/delete")
public class DeleteBlog extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求格式
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //获取session会话
        HttpSession session = req.getSession();
        if (session == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录!");
            return;
        }
        //获取user对象
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录!");
            return;
        }
        //获取该博客的blogId
        int blogId = Integer.parseInt(req.getParameter("blogId"));
        //获取blog信息
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(blogId);
        //比较userId是否一致(检测当前用户是否为作者，只有博客作者可以删除自己的文章)
        if(blog.getUserId() != blog.getUserId()) {
            resp.setStatus(403);
            resp.getWriter().write("这不是你的博客，不可以删除!");
            return;
        }
        //删除博客
        blogDao.delete(blogId);
        //重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
